package com.elh.nio.bytebuffer;

import org.junit.jupiter.api.Test;

import java.nio.ByteBuffer;

/**
 * @author liulei
 **/
public class BufferTest {

    /**
     * 测试buffer中的limit:
     * 1.表示缓存冲限制,第一个不应该可以读取或者写入的索引
     * 2.换句话就是只有limit之前的索引才可以读取或者写入
     *
     */
    @Test
    public void test1(){
        byte[] byteArray = new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9};
        ByteBuffer byteBuffer = ByteBuffer.wrap(byteArray);
//        byteBuffer.limit(3);
        byteBuffer.put((byte) 12);
        System.out.println(byteBuffer.position());
        System.out.println(byteBuffer.limit());
        System.out.println(byteBuffer.capacity());
        byteBuffer.put((byte) 22);
        byteBuffer.put((byte) 33);
        System.out.println(byteBuffer.get());
    }


    /**
     * 判断是否直接缓冲区
     *
     */
    @Test
    public void test2(){
        ByteBuffer byteBuffer = ByteBuffer.allocateDirect(100);
        System.out.println(byteBuffer.isDirect());
    }

    /**
     * 测试clear方法
     *
     */
    @Test
    public void test3(){
        byte[] byteArray = new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9};
        ByteBuffer wrap = ByteBuffer.wrap(byteArray);
        System.out.println(wrap.position());
        System.out.println(wrap.limit());
        System.out.println(wrap.capacity());
        wrap.put((byte) 1);
        wrap.clear();
    }

    /**
     * 测试直接缓存区
     *
     */
    @Test
    public void test4(){
        long start = System.currentTimeMillis();
        ByteBuffer byteBuffer = ByteBuffer.allocateDirect(1900000000);
        for (int i = 0; i < 1900000000; i++) {
            byteBuffer.put((byte) 123);
        }
        long end = System.currentTimeMillis();
        System.out.println(end - start);
    }

    /**
     * 测试非直接缓存区
     *
     */
    @Test
    public void test5(){
        long start = System.currentTimeMillis();
        ByteBuffer byteBuffer = ByteBuffer.allocate(1900000000);
        for (int i = 0; i < 1900000000; i++) {
            byteBuffer.put((byte) 123);
        }
        long end = System.currentTimeMillis();
        System.out.println(end - start);
    }

    @Test
    public void test6(){
        byte[] b = {1,2,3,4,5,6,7,8};
        ByteBuffer wrap = ByteBuffer.wrap(b);
        wrap.position(4);
        ByteBuffer slice = wrap.slice();
        System.out.println("position = " + slice.position() + "capacity" + wrap.capacity() + "limit" + slice.limit());
    }

    /**
     * 压缩缓冲区
     *
     */
    @Test
    public void test7(){
        byte[] b = {1,2,3,4,5,6,7,8};
        ByteBuffer wrap = ByteBuffer.wrap(b);
        wrap.position(4);
        ByteBuffer duplicate = wrap.duplicate();
        System.out.println("position = " + duplicate.position() + "capacity" + wrap.capacity() + "limit" + duplicate.limit());
    }







}
